//
//  YXAppDelegate.m
//  跑跑快销
//
//  Created by 杨潇 on 14-4-28.
//  Copyright (c) 2014年 ylife. All rights reserved.
//

#import "YXAppDelegate.h"
#import "YXLoginViewController.h"

@implementation YXAppDelegate

void uncaughtExceptionHandler(NSException *exception) {
    NSLog(@"CRASH: %@", exception);
    NSLog(@"Stack Trace: %@", [exception callStackSymbols]);
    // Internal error reporting
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.window endEditing:YES];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UILocalNotification * localNoti = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNoti) {
        [self cancelNotificationWith:localNoti];
    }
//    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [WXApi registerApp:@"wxb5f40940dcb39f5f"];
    
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"COr3zjio6IktYlG3ialOteea"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    YXWindowInfo * windowInfo = [YXWindowInfo sharedWindowInfo];
    windowInfo.requestUrlStr = @"http://192.168.1.222:88/CRM.ashx";
    windowInfo.userAccount = @"UserAccount";
    windowInfo.userPassword = @"UserPassword";

    YXLoginViewController * loginVC = [[YXLoginViewController alloc] init];
    self.window.rootViewController = loginVC;
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    _notification = notification;
    _isVibrate = YES;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
        NSString * path = [[NSBundle mainBundle] pathForResource:@"cnhk" ofType:@"m4r"];
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
        [_player prepareToPlay];
        [_player setVolume:1];
        [_player play];
        
        while (_isVibrate) {
            [NSThread sleepForTimeInterval:1];
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        }
    });
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"闹铃" message:notification.alertBody delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
    alert.delegate = self;
    [alert show];
}

- (void)cancelNotificationWith:(UILocalNotification *)notification
{
    NSMutableDictionary * infoDic = [NSMutableDictionary dictionaryWithContentsOfFile:[notification.userInfo objectForKey:@"path"]];
    if (infoDic) {
        NSString * alarmDate = [infoDic objectForKey:[notification.userInfo objectForKey:@"key"]];
        if (alarmDate) {
        [infoDic removeObjectForKey:[notification.userInfo objectForKey:@"key"]];
        [infoDic writeToFile:[notification.userInfo objectForKey:@"path"] atomically:YES];
        }
    }

    [[UIApplication sharedApplication] cancelLocalNotification:notification];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [_player stop];
    _isVibrate = NO;
    [self cancelNotificationWith:_notification];
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
